const {
  getCommentList,
  addUserComment,
  addOtherComment,
  getOtherCommentList,
  getAdminIsNoComList,
  changeAdminisComment,
  addReplyAdmin,
  delReplayAdminById,
  getNocomInfo,
  getOtherNoCom,
  deleteOneReply,
} = require("../dao/newMessageDao");
const { uFilterSenWords } = require("../utils/uFilterSensitiveWords");
const { updateCommentNum } = require("../dao/blogDao");
const { formatResponse } = require("../utils/tool");
const crypto = require("crypto");
const sd = require("silly-datetime");
const base = `https://www.fangq.site/img/static/`;
const fs = require("fs");
const adminInfo = {
  username: "admin",
  userpassword: "123456",
  userimg: "rootimg/root.jpg",
};
module.exports.getCommentListServer = async (articleId) => {
  const result = await getCommentList(articleId);
  if (result.length == 0) {
    return formatResponse(0, "暂无评论", []);
  } else {
    return formatResponse(0, "查询成功", {
      list: result[0].itemArticleComment,
    });
  }
};

module.exports.getUserImgList = () => {
  let baseUrl = base + "userimg/";
  return new Promise((resolve, reject) => {
    fs.readdir("./public/static/userimg", (err, file) => {
      if (err) {
        resolve(formatResponse(0, "用户头像获取失败", {}));
      }
      resolve(
        formatResponse(0, "用户头像数据获取成功", { list: file, url: baseUrl })
      );
    });
  });
};
//定义层主级别的回复
module.exports.addUserCommentServer = async (reqData) => {
  // 文章id
  let articleId = reqData.articleId;
  //时间
  let nowCommentTime = sd.format(new Date(), "YYYY-MM-DD HH:mm");

  //提交的信息
  let info = {
    // 层主评论
    userImg: base + "userimg/" + reqData.userImg, //头像
    userName: reqData.userName, //昵称
    commentTime: nowCommentTime, //发布时间
    commentCont: reqData.commentCont, //评论内容
    commentPoint: adminInfo.username, //层主评论的指向admin
    commentNumber: 0, //回复数量
    adminisComment: false,
  };
  //敏感词过滤
  try {
    info.commentCont = await uFilterSenWords(info.commentCont);
  } catch (e) {
    throw new ValidationError("敏感词过滤失败");
  }
  await updateCommentNum(articleId, false, false, "sum");
  await addUserComment(articleId, info);
  return formatResponse(0, "评论成功", info);
};
// 定义一个楼层中其他用户的评论(管理员回复)
module.exports.addOtherCommentServer = async (reqData) => {
  // 文章id
  let articleId = reqData.articleId;
  //楼层id
  let ceID = reqData.ceID;
  //时间
  let nowCommentTime = sd.format(new Date(), "YYYY-MM-DD HH:mm");
  //当前回复的对象是否为管理员
  let replayObjIsadmin = reqData.replayObjIsadmin;

  //此时发布层级下其他用户回复管理员的情况
  let replyOtherByAdmin = !!reqData.replyOtherByAdmin;
  //提交的信息
  let info = {
    commentTime: nowCommentTime, //发布时间
    commentCont: reqData.commentCont, //评论内容
    commentPoint: reqData.commentPoint, //评论的指向
    isadmin: false,
    id:crypto.randomBytes(16).toString("hex")
  };
  //此时为管理员回复
  if ((reqData.isadmin && reqData.isadmin !== "false")|| reqData.isadmin === "true") {
    info.userImg = base + "rootimg/root.jpg";
    info.userName = adminInfo.username;
    info.isadmin = true;
  } else {
    // 层主评论
    info.userImg = base + "userimg/" + reqData.userImg; //头像
    info.userName = reqData.userName; //昵称
  }
  //由于层主级别的回复使用了dom渲染的方式，并不是从服务器中请求的数据，所以此时ceID为undefined
  if (!reqData.ceID) {
    return formatResponse(402, "回复失败，请退出后重新回复", null);
  }
  //非管理员进行敏感词过滤
  try {
    if (!info.isadmin) {
      info.commentCont = await uFilterSenWords(info.commentCont);
    }
  } catch (e) {
    throw new ValidationError("敏感词过滤失败");
  }
  let isadm = 0;
  //更新文章评论数量
  await updateCommentNum(articleId, true, false, "sum");
  //新增回复
  await addOtherComment(articleId, reqData.ceID, info);
  //需要修改文章中未回复的数量
  if (reqData.isadmin) {
    isadm = 1;
    await updateCommentNum(articleId, false, true, "sub");
  }
  //层主评论中adminisComment的属性
  if (isadm == 1) {
    await changeAdminisComment(articleId, ceID);
  }
  //楼层中回复管理员的情况
  if (replayObjIsadmin) {
    await addReplyAdmin({
      articleId,
      ceID,
      userImg: base + "userimg/" + reqData.userImg,
      userName: reqData.userName,
      commentTime: nowCommentTime,
      commentCont: reqData.commentCont,
      commentPoint: reqData.commentPoint,
      adminisComment: false,
      oldreplyCon: reqData.oldreplyCon,
    });
    await updateCommentNum(articleId, false, true, "sum");
  }
  //管理员回复楼层中的用户
  if (replyOtherByAdmin) {
    let id = reqData.needDelId;
    await delReplayAdminById(id);
  }
  info.ceID = reqData.ceID;
  return formatResponse(0, "回复成功", info);
};

//渲染其他用户的评论列表
module.exports.getOtherCommentListServer = async (ceId) => {
  //从数据库中查找评论列表
  const result = await getOtherCommentList(ceId);
  if (result.length == 0) {
    return formatResponse(0, "暂无回复", result);
  } else {
    return formatResponse(0, "查询成功", { list: result[0].replyCon });
  }
};
//获取含有管理员未回复的文章列表
module.exports.getAdminIsNoComListServer = async () => {
  const result = await getAdminIsNoComList();
  return formatResponse(0, "获取含有管理员未回复success", { list: result });
};

//根据文章id获取未回复的评论信息
module.exports.getNoComListServer = async (articleId) => {
  let p1 = getNocomInfo(articleId);
  let p2 = getOtherNoCom(articleId);
  let result = await Promise.all([p1, p2]);
  return formatResponse(0, "查询成功", { list: result });
};
module.exports.deleteOneReplyServer = async (articleId, ceID, id) => {
  await deleteOneReply(articleId, ceID, id);
  return formatResponse(0, "删除成功", null);
};